In Python, function parameters can have default values.
These default values are expressions which are evalutated when the function is defined, i.e. only once. The same default value will be used every
time the function is called. Therefore, modifying it will have an effect on every subsequent call. This can lead to confusing bugs.
def myfunction(param=foo()): # foo is called only once, when the function is defined.
...
For the same reason, it is also a bad idea to store mutable default values in another object (ex: as an attribute). Multiple instances will then
share the same value and modifying one object will modify all of them.
This rule raises an issue when:
- a default value is either modified in the function or assigned to anything other than a variable and it has one of the following types:
- collections module: deque, UserList, ChainMap, Counter, OrderedDict,
defaultdict, UserDict.
- an attribute of a default value is assigned.
Exceptions
In some rare cases, modifying a default value is intentional. For example, default values can be used as a cache.
No issue will be raised when the parameter’s name contains "cache" or "memo" (as in memoization).